<template>
  <div class="center">
    <el-row :gutter="20" type="flex" justify="center">
      <el-col>
        <div class="infoFrom changedialog">
          <el-form ref="infoForm" :model="infoForm" label-width="100px" size="mini" :rules="rules">
            <el-form-item label-width="0">
              <div class="flex flex_cen" style="align-items: flex-end">
                <div class="infoImg">
                  <img :src="infoForm.avatar ? infoForm.avatar : imgInfo" alt />
                </div>
                <my-upload ref="myUpload" field="file" @crop-success="cropSuccess" @crop-upload-success="cropUploadSuccess" @crop-upload-fail="cropUploadFail" v-model="show" :width="100" :height="100"
                  :url="`${uploadLink}api/uploadPreviewImg`" :params="params"></my-upload>
              </div>
              <div style="text-align: center;margin-top: 10px;">
                <el-button icon="el-icon-upload" @click="toggleShow">编辑头像</el-button>
              </div>
            </el-form-item>
            <el-form-item label="用户名:" prop="username">
              <el-input v-model="infoForm.username" placeholder="请输入用户名" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="Email:" prop="email">
              <el-input v-model="infoForm.email" placeholder="请输入邮箱" ></el-input>
            </el-form-item>
            <el-form-item label="昵称:" prop="realname">
              <el-input v-model="infoForm.realname" name="mobile" readonly onfocus="this.removeAttribute('readonly')" autocomplete="off" class="add_select" placeholder="请输入真实姓名" :maxlength="12" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input ref="changePassword" v-model="infoForm.password" name="password" readonly onfocus="this.removeAttribute('readonly')" autocomplete="off" class="add_select" placeholder="请输入密码" :maxlength="53"
                :key="changeType" :type="changeType" />
              <span class="show-pwd" @click="changeshowPwd">
                <svg-icon :icon-class="changeType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
            <el-form-item label="地址:" prop="address">
              <el-input v-model="infoForm.address" placeholder="请输入地址"></el-input>
            </el-form-item>
            <el-form-item label="手机号码:" prop="mobile">
              <div class="addPut">
                <el-input v-model="infoForm.mobile" placeholder="请输入手机号码" disabled></el-input>
                <div class="dlePut phoneBtn" @click="getMobileShow">修改手机</div>
              </div>
            </el-form-item>
            <el-form-item label="新手机号码:" v-if="mobileShow" prop="newMobile">
              <div class="addPut">
                <el-input v-model="infoForm.newMobile" placeholder="请输入新手机号码"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="验证码:" prop="code" v-if="passwordShow">
              <div class="addPut">
                <el-input v-model="infoForm.code" placeholder="请输入验证码"></el-input>
                <el-button class="dlePut phoneBtn" size="mini" round style="padding:2px 6px" @click="sendcode" :disabled="!codeShow">{{codeShow ? '获取验证码' : count + 's'}}</el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <Debounce :time='500' :isDebounce="3">
                <el-button type="primary" @click.native="infosubmitForm('infoForm')">提交</el-button>
              </Debounce>
              <el-button @click="inforesetForm('infoForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { LOG, phoneSms, UserIdInfo, updateUserIdInfo } from "@/api/infos.js";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import myUpload from 'vue-image-crop-upload';
import 'babel-polyfill'; // es6 shim
import addFromVue from '../../application/component/addFrom.vue';
import { antiShake } from '@/utils/throttle'
export default {
  components: { dynamicTable, myUpload },
  data() {
    var phoneReg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('号码不能为空!!'))
      }
      if (!phoneReg.test(value)) {
        callback(new Error('手机号码有误'))
      } else {
        callback()
      }
    };
    var emailReg = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
    var validatorEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空!!'))
      }
      if (!emailReg.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    };
    return {
      changeType: "password",
      checkboxVal: ["ID", "标题", "ip", "操作时间"],
      key: 1,
      colData: [], //动态控制table
      avatar: '',
      //用户名表单
      infoForm: {
        username: "",
        email: "",
        realname: "",
        password: "",
        mobile: "",
        avatar: "",
        code: "",
        address: "",
        newMobile: ""
      },
      rules: {
        email: [{ required: true, validator: validatorEmail, trigger: ['blur', 'change'] }],
        realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        newMobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        password: [{ min: 6, max: 12, message: '请输入6至12位之间的密码', trigger: 'blur' }],
      },
      //日志表格
      logtableData: [],
      //日志搜索
      input3: "",
      select: "",
      total: 0, //总数量
      show: false,//上传头像视图
      params: { last_ip: '', userId: '' },
      codeShow: true,//验证码按钮
      count: '',//验证码倒计时
      timer: null,
      mobile: '',
      mobileShow: false,
      imgInfo: require('../../../assets/images/definfo.png'),//默认用户图片
      uploadLink: process.env.VUE_APP_BASE_API
    };
  },
  computed: {
    passwordShow() {
      return this.infoForm.password ? true : false
    }
  },
  mounted() {

  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.params.last_ip = sessionStorage.getItem("Ip")
    this.params.userId = localStorage.getItem("ID")
    this.getUserIdInfo()
  },
  methods: {
    getMobileShow() {
      this.mobileShow = !this.mobileShow
    },
    changeshowPwd(type) {
      if (this.changeType === "password") {
        this.changeType = "";
      } else {
        this.changeType = "password";
      }
      this.$nextTick(() => {
        this.$refs.changePassword.focus();
      })
    },
    //获取用户个人信息
    getUserIdInfo() {
      UserIdInfo({ userId: localStorage.getItem("ID") }).then(res => {
        let data = res.data
        this.$store.commit('user/SET_AVATAR', data.avatar == null ? JSON.stringify(data.avatar) : data.avatar)
        localStorage.setItem('avatar', data.avatar == null ? JSON.stringify(data.avatar) : data.avatar)
        Object.keys(this.infoForm).forEach(key => { this.infoForm[key] = data[key] })
        this.mobile = data.mobile
      })
    },
    //获取验证码
    sendcode() {
      let reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
      if (this.infoForm.mobile == '') return this.$message.error('请先输入手机号码')
      if (!reg.test(this.infoForm.mobile)) return this.$message.error('请输入正确的手机号码')
      this.verification()
    },
    //发送验证码
    verification() {
      phoneSms({ phone: this.mobile, userId: localStorage.getItem("ID") }).then(res => {
        this.$message.success(res.msg)
      }).catch(err => {
        //this.$message.error(err.msg)
      })
      const TIME = 60
      if (!this.count) {
        this.count = TIME
        this.codeShow = false
      }
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME) {
          this.count = this.count - 1
        } else {
          this.codeShow = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    toggleShow() {
      this.show = !this.show;
    },
    //上传成功回调
    cropUploadSuccess(jsonData, field) {
      if (jsonData.code == 200) {
        this.infoForm.avatar = jsonData.data.imgPath
        this.$refs.myUpload.off()
      }
    },
    cropSuccess(img) {
      this.infoForm.avatar = img
    },
    //上传失败回调
    cropUploadFail(status, field) {
      console.log('上传失败状态' + status);
      console.log('field: ' + field);
    },
    infosubmitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let infoForm = JSON.parse(JSON.stringify(this.infoForm))
          delete infoForm.username
          infoForm.userId = localStorage.getItem("ID")
          infoForm.last_ip = sessionStorage.getItem("Ip")
          infoForm.password != '' ? infoForm.password : delete infoForm.password
          infoForm.newMobile ? (infoForm.mobile = infoForm.newMobile) && (delete infoForm.newMobile) : delete infoForm.newMobile
          updateUserIdInfo(infoForm).then(res => {
            this.$message.success(res.msg)
            if (this.passwordShow) {
              setTimeout(async () => {
                await this.$store.dispatch('user/logout')
                this.$router.push(`/login?redirect=${this.$route.fullPath}`)
              }, 1000)
            } else {
              this.getUserIdInfo()
            }
          }).catch(err => {
            this.getUserIdInfo()
            console.log('失败', err)
          })
        } else {
          return false;
        }
      });
    },
    inforesetForm(formName) {
      this.$refs[formName].resetFields();
      this.getUserIdInfo()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.infoFrom {
  padding: 40px;
}
.infoImg {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  overflow: hidden;
  img {
    width: 100%;
    height: 100%;
  }
}
.phoneBtn {
  top: 50%;
  transform: translate(0, -50%);
  font-size: 12px;
  right: 5px;
  border: 1px solid #dcdfe6;
  color: #606266;
  line-height: 16px;
  padding: 1px 10px;
  border-radius: 4px;
  cursor: pointer;
}
.changedialog {
  width: 35%;
  // position: relative;
  // left: 50%;
  // top: 50%;
  // transform: translate(-50%, -50%);
  margin: 0 auto;
  text-align: center;
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
    color: #dcdfe6;
  }
}
</style>

<style scoped>
.table_select .el-input {
  width: 100px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
/deep/.vue-image-crop-upload .vicp-wrap {
  border-radius: 8px;
}
/deep/ .vue-image-crop-upload .vicp-wrap .vicp-operate {
  background-color: #fff;
  border-radius: 4px;
}
/deep/ .vue-image-crop-upload .vicp-wrap .vicp-operate a {
  color: #fff;
  background-color: #409eff;
}
</style>